package de.havre.wakeupnas.nas;

import java.io.File;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.TimerTask;

import de.havre.wakeupnas.Config;

class NasTask extends TimerTask {

	private NasController controller;

	public NasTask(NasController controller) {
		this.controller = controller;
	}

	public static final int PORT = 9;

	public void run() {
		String nasaddress = "192.168.0.12";
		String ipStr = "192.168.0.255";
		String macStr = "00:24:A5:9A:00:DD";

		/* WAKE UP NAS */
		try {

			
			byte[] macBytes = getMacBytes(macStr);
			byte[] bytes = new byte[6 + 16 * macBytes.length];
			for (int i = 0; i < 6; i++) {
				bytes[i] = (byte) 0xff;
			}
			for (int i = 6; i < bytes.length; i += macBytes.length) {
				System.arraycopy(macBytes, 0, bytes, i, macBytes.length);
			}

			InetAddress address = InetAddress.getByName(ipStr);
			DatagramPacket packet = new DatagramPacket(bytes, bytes.length,
					address, PORT);
			DatagramSocket socket = new DatagramSocket();
			socket.send(packet);
			socket.close();

			System.out.println("Wake-on-LAN packet sent.");
		} catch (Exception e) {
			System.out.println("Failed to send Wake-on-LAN packet: + e");
			System.exit(1);
		}

		/* PING NAS */
//		try {
//			boolean reachable = InetAddress.getByName(nasaddress).isReachable(3000);
//			if (reachable) {
//				controller.notifyNasIsOnline();
//			}
//
//		} catch (UnknownHostException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		/* check nas file */
		try {
			Properties p = Config.getProperties();
			String checkfile = (String) p.getProperty("checkfile");
			File checkfileFile = new File(checkfile);
			if (checkfileFile.exists()) {
				controller.notifyNasIsOnline();
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		

	}

	private byte[] getMacBytes(String macStr) throws IllegalArgumentException {
		byte[] bytes = new byte[6];
		String[] hex = macStr.split("(\\:|\\-)");
		if (hex.length != 6) {
			throw new IllegalArgumentException("Invalid MAC address.");
		}
		try {
			for (int i = 0; i < 6; i++) {
				bytes[i] = (byte) Integer.parseInt(hex[i], 16);
			}
		} catch (NumberFormatException e) {
			throw new IllegalArgumentException(
					"Invalid hex digit in MAC address.");
		}
		return bytes;
	}
}
